/**
 * TicketBooking.java
 *
 * This program demonstrates the use of built-in methods to insert, update and delete records to display the details of
 * each employee.
 *
 * Copyright � 2007 Aptech Software Limited. All Rights Reserved.
 */
package practice.airlinebooking;

import java.awt.Color;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.StringTokenizer;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.MaskFormatter;

/**
 * TicketBooking is a class to display the records of each passenger whose tickets has been booked earlier.
 *
 * @author vincent
 */
public class TicketBooking extends javax.swing.JFrame {

    /**
     * Creates new form TicketBooking
     */
    public TicketBooking() {

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows."
                    + "WindowsLookAndFeel");
            UIManager.put("Button.showMnemonics", Boolean.TRUE);
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        getContentPane().setBackground(new Color(212, 208, 200));

        try {

            // Load a Type 4 driver for connecting to SQL Server 2005 database.
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

            // Obtain a connection to the database.
            cn = DriverManager.getConnection(getConnectionUrl(), userName,
                    password);

            // PreparedStatement object for sending the SQL statement
            // to the database.
            pstDetails = cn.prepareStatement("Select * from TicketBooking",
                    ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

            // Execute SQL statement in PreparedStatement object and return
            // the ResultSet object generated by the query.
            rsDetails = pstDetails.executeQuery();

            if (cn != null) {
                System.out.println("Connection Successful!");
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        // Creates an instance of class JOptionPane
        JOptionPane dialog = new JOptionPane();

        initComponents();
    }

    /**
     * This method returns the URL for the SQL Server 2005 database.
     *
     * @return The string containing the URL, server name, instance name and database name.
     */
    private String getConnectionUrl() {
        return url + serverName + ";instanceName=" + instanceName
                + ";databaseName=" + databaseName;
    }

    /**
     * This method is invoked to close the connection.
     */
    private void closeConnection() {
        try {
            if (cn != null) {
                cn.close();
            }
            cn = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
     * content of this method is always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlHeading = new javax.swing.JPanel();
        lblHeading = new javax.swing.JLabel();
        pnlBookingDetails = new javax.swing.JPanel();
        lblName = new javax.swing.JLabel();
        txtName = new javax.swing.JTextField();
        lblContactNumber = new javax.swing.JLabel();
        txtContactNo = new javax.swing.JTextField();
        lblAddress = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txaAddress = new javax.swing.JTextArea();
        lblNumberofTickets = new javax.swing.JLabel();
        txtNumberOfTickets = new javax.swing.JTextField();
        btnBookTicket = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnExit = new javax.swing.JButton();
        pnlPaymentDetails = new javax.swing.JPanel();
        lblCreditCardNo = new javax.swing.JLabel();
        lblExpiryDate = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        try{
            cardNumber = new MaskFormatter("####-####-####-####");
        }catch(java.text.ParseException e){
            e.printStackTrace();
        }
        txfCreditCardNo = new JFormattedTextField(cardNumber);
        txfExpiryDate = new JFormattedTextField(new SimpleDateFormat("yyyy-mm-dd"));
        txfExpiryDate.setValue(new java.sql.Date(time));
        txfExpiryDate.setText("");
        pnlGoToRecord = new javax.swing.JPanel();
        lblGoToRecord = new javax.swing.JLabel();
        txtGoToRecord = new javax.swing.JTextField();
        btnGo = new javax.swing.JButton();
        btnCancelTicket = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("United Airlines");
        setResizable(false);
        getContentPane().setLayout(null);

        pnlHeading.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        pnlHeading.setLayout(null);

        lblHeading.setFont(new java.awt.Font("Microsoft Sans Serif", 1, 14)); // NOI18N
        lblHeading.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblHeading.setText("Welcome to United Airlines");
        pnlHeading.add(lblHeading);
        lblHeading.setBounds(40, 0, 270, 20);

        getContentPane().add(pnlHeading);
        pnlHeading.setBounds(20, 10, 360, 25);

        pnlBookingDetails.setBorder(javax.swing.BorderFactory.createTitledBorder("Booking Details"));
        pnlBookingDetails.setLayout(null);

        lblName.setText("Name:");
        pnlBookingDetails.add(lblName);
        lblName.setBounds(20, 30, 34, 20);
        pnlBookingDetails.add(txtName);
        txtName.setBounds(130, 30, 210, 20);

        lblContactNumber.setText("Contact Number:");
        pnlBookingDetails.add(lblContactNumber);
        lblContactNumber.setBounds(20, 60, 100, 20);
        pnlBookingDetails.add(txtContactNo);
        txtContactNo.setBounds(130, 60, 210, 20);

        lblAddress.setText("Address:");
        pnlBookingDetails.add(lblAddress);
        lblAddress.setBounds(20, 90, 60, 20);

        txaAddress.setColumns(20);
        txaAddress.setFont(new java.awt.Font("Microsoft Sans Serif", 0, 11)); // NOI18N
        txaAddress.setLineWrap(true);
        txaAddress.setRows(3);
        jScrollPane1.setViewportView(txaAddress);

        pnlBookingDetails.add(jScrollPane1);
        jScrollPane1.setBounds(130, 90, 210, 40);

        lblNumberofTickets.setText("Number of tickets to be booked:");
        pnlBookingDetails.add(lblNumberofTickets);
        lblNumberofTickets.setBounds(20, 150, 160, 20);
        pnlBookingDetails.add(txtNumberOfTickets);
        txtNumberOfTickets.setBounds(190, 150, 57, 20);

        getContentPane().add(pnlBookingDetails);
        pnlBookingDetails.setBounds(20, 50, 360, 190);

        btnBookTicket.setText("Book Ticket");
        btnBookTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBookTicketActionPerformed(evt);
            }
        });
        getContentPane().add(btnBookTicket);
        btnBookTicket.setBounds(50, 380, 87, 23);

        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });
        getContentPane().add(btnUpdate);
        btnUpdate.setBounds(280, 380, 67, 23);

        btnExit.setText("Exit");
        btnExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnExitActionPerformed(evt);
            }
        });
        getContentPane().add(btnExit);
        btnExit.setBounds(180, 380, 51, 23);

        pnlPaymentDetails.setBorder(javax.swing.BorderFactory.createTitledBorder("Payment Details"));
        pnlPaymentDetails.setLayout(null);

        lblCreditCardNo.setText("Credit Card Number:");
        pnlPaymentDetails.add(lblCreditCardNo);
        lblCreditCardNo.setBounds(20, 30, 100, 20);

        lblExpiryDate.setText("Expiry Date:");
        pnlPaymentDetails.add(lblExpiryDate);
        lblExpiryDate.setBounds(20, 70, 100, 20);

        jLabel1.setText("(yyyy-mm-dd)");
        pnlPaymentDetails.add(jLabel1);
        jLabel1.setBounds(280, 70, 60, 20);
        pnlPaymentDetails.add(txfCreditCardNo);
        txfCreditCardNo.setBounds(130, 30, 140, 20);
        pnlPaymentDetails.add(txfExpiryDate);
        txfExpiryDate.setBounds(130, 70, 140, 20);

        getContentPane().add(pnlPaymentDetails);
        pnlPaymentDetails.setBounds(20, 250, 360, 110);

        pnlGoToRecord.setBorder(javax.swing.BorderFactory.createTitledBorder("Show Record"));
        pnlGoToRecord.setLayout(null);

        lblGoToRecord.setText("Go to specific record:");
        lblGoToRecord.setPreferredSize(new java.awt.Dimension(102, 20));
        pnlGoToRecord.add(lblGoToRecord);
        lblGoToRecord.setBounds(20, 30, 110, 20);
        pnlGoToRecord.add(txtGoToRecord);
        txtGoToRecord.setBounds(130, 30, 57, 20);

        btnGo.setMnemonic('G');
        btnGo.setText("Go");
        btnGo.setToolTipText("Click here to display the corresponding record details.");
        btnGo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGoActionPerformed(evt);
            }
        });
        pnlGoToRecord.add(btnGo);
        btnGo.setBounds(220, 30, 73, 23);

        btnCancelTicket.setText("Cancel Ticket");
        btnCancelTicket.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelTicketActionPerformed(evt);
            }
        });
        pnlGoToRecord.add(btnCancelTicket);
        btnCancelTicket.setBounds(120, 70, 95, 23);

        getContentPane().add(pnlGoToRecord);
        pnlGoToRecord.setBounds(20, 420, 360, 100);

        setSize(new java.awt.Dimension(408, 562));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * This method is invoked to cancel the booked ticket by deleting a specific record from the ResultSet.
     *
     * @param evt ActionEvent object to store information about the click on the Cancel Ticket button.
     */
  private void btnCancelTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelTicketActionPerformed
// TODO add your handling code here:
      // Check if all the fields contains valid data
      if ((txtName.getText().length() != 0)
              && (txtContactNo.getText().length() != 0)
              && (txaAddress.getText().length() != 0)
              && (txtNumberOfTickets.getText().length() != 0)
              && (txfCreditCardNo.getText().length() != 0)
              && (txfExpiryDate.getText().length() != 0)) {

          try {
              int record = Integer.valueOf(txtGoToRecord.getText());
              rsDetails.absolute(record);
              int option;
              option = JOptionPane.showConfirmDialog(this, "Are you sure you "
                      + "want to delete the record?", "Confirm",
                      JOptionPane.YES_NO_OPTION);
              if (option == JOptionPane.YES_OPTION) {
                  rsDetails.deleteRow();
                  JOptionPane.showMessageDialog(null, "Record Deleted!!!");
                  txtName.setText("");
                  txtContactNo.setText("");
                  txaAddress.setText("");
                  txtNumberOfTickets.setText("");
                  txfCreditCardNo.setText("");
                  txfExpiryDate.setText("");
              } else {
                  rsDetails.first();
                  txtName.setText("");
                  txtContactNo.setText("");
                  txaAddress.setText("");
                  txtNumberOfTickets.setText("");
                  txfCreditCardNo.setText("");
                  txfExpiryDate.setText("");
              }
          } catch (NumberFormatException ex) {
              ex.printStackTrace();
          } catch (HeadlessException ex) {
              ex.printStackTrace();
          } catch (SQLException ex) {
              ex.printStackTrace();
          }
      } else {
          JOptionPane.showMessageDialog(null, "Display the record to be "
                  + "deleted!!!");
      }
  }//GEN-LAST:event_btnCancelTicketActionPerformed

    /**
     * This method is used to exit the application and to close all the JDBC resources.
     *
     * @param evt ActionEvent object to store information about the click on the Exit button.
     */
  private void btnExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnExitActionPerformed
// TODO add your handling code here:

      try {
          cn.commit();
          closeConnection();
          rsDetails.close();
      } catch (SQLException ex) {
          ex.printStackTrace();
      }
      System.exit(0);
  }//GEN-LAST:event_btnExitActionPerformed

    /**
     * This method is used to edit an existing record and save the respective changes in the database.
     *
     * @param evt ActionEvent object to store information about the click on the Update button.
     */
  private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:

      // Check if the user has entered all the data required
      if ((txtName.getText().length() != 0)
              && (txtContactNo.getText().length() != 0)
              && (txaAddress.getText().length() != 0)
              && (txtNumberOfTickets.getText().length() != 0)
              && (txfCreditCardNo.getText().length() != 0)
              && (txfExpiryDate.getText().length() != 0)) {

          // Check if the user has entered a valid date and credit card number
          if ((txfCreditCardNo.isEditValid()) && (txfExpiryDate.isEditValid())) {

              String strDate = txfExpiryDate.getText();
              java.sql.Date d = java.sql.Date.valueOf(txfExpiryDate.getText());
              Calendar enteredDate = Calendar.getInstance();
              enteredDate.setTime(d);
              Calendar calendar = Calendar.getInstance();
              java.util.Date currentDate = calendar.getTime();
              boolean valid = d.after(currentDate);

              if (valid) {
                  try {
                      rsDetails.updateString(1, txtName.getText());
                      rsDetails.updateLong(2, Long.parseLong(txtContactNo.
                              getText().trim()));
                      rsDetails.updateString(3, txaAddress.getText());
                      rsDetails.updateInt(4, Integer.valueOf(txtNumberOfTickets.
                              getText()));
                      StringTokenizer st = new StringTokenizer(txfCreditCardNo.
                              getText());
                      while (st.hasMoreTokens()) {
                          temp = temp + st.nextToken("-");
                      }
                      rsDetails.updateLong(5, Long.parseLong(temp));

                      if (txfExpiryDate.isEditValid()) {
                          d = java.sql.Date.valueOf(txfExpiryDate.getText());
                          rsDetails.updateDate(6, d);
                      }
                      rsDetails.updateRow();
                      JOptionPane.showMessageDialog(null, "Record Updated!!");
                      txtName.setText("");
                      txtContactNo.setText("");
                      txaAddress.setText("");
                      txtNumberOfTickets.setText("");
                      txfCreditCardNo.setText("");
                      txfExpiryDate.setText("");
                      txtGoToRecord.setText("");
                  } catch (NumberFormatException ex) {
                      ex.printStackTrace();
                  } catch (HeadlessException ex) {
                      ex.printStackTrace();
                  } catch (SQLException ex) {
                      ex.printStackTrace();
                  }
              } else {
                  JOptionPane.showMessageDialog(null, "Credit card has "
                          + "expired!!");
              }
          }
      } else {
          JOptionPane.showMessageDialog(null, "Enter all the details to "
                  + "book the ticket!");
      }
  }//GEN-LAST:event_btnUpdateActionPerformed

    /**
     * Method to display a specific record from the ResultSet.
     *
     * @param evt ActionEvent object to display information about the click on the Go button.
     */
  private void btnGoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGoActionPerformed
// TODO add your handling code here:

      // Check if the user has entered any value in the text field.
      if (txtGoToRecord.getText().length() == 0) {
          JOptionPane.showMessageDialog(null, "Enter a record number "
                  + "to view its detail!");
      } else {
          try {
              int record = Integer.valueOf(txtGoToRecord.getText());
              rsDetails.last();
              int noOfRows = rsDetails.getRow();
              if ((record - 1 < noOfRows) && (record > 0)) {
                  rsDetails.absolute(record);
                  txtName.setText(rsDetails.getString(1));
                  txtContactNo.setText(rsDetails.getString(2));
                  txaAddress.setText(rsDetails.getString(3));
                  txtNumberOfTickets.setText(rsDetails.getString(4));
                  txfCreditCardNo.setText(rsDetails.getString(5));
                  txfExpiryDate.setText(rsDetails.getDate(6).toString());
              } else {
                  JOptionPane.showMessageDialog(null, "The record does not "
                          + "exist in the database!!!");
              }
          } catch (HeadlessException ex) {
              ex.printStackTrace();
          } catch (NumberFormatException ex) {
              ex.printStackTrace();
          } catch (SQLException ex) {
              ex.printStackTrace();
          }
      }
  }//GEN-LAST:event_btnGoActionPerformed

    /**
     * This method is invoked when a new ticket is to be booked.
     *
     * @param evt ActionEvent object to store information about the click on the Book Ticket button.
     */
  private void btnBookTicketActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBookTicketActionPerformed
// TODO add your handling code here:

      // Check if the user has entered all the data required
      if ((txtName.getText().length() != 0)
              && (txtContactNo.getText().length() != 0)
              && (txaAddress.getText().length() != 0)
              && (txtNumberOfTickets.getText().length() != 0)
              && (txfCreditCardNo.getText().length() != 0)
              && (txfExpiryDate.getText().length() != 0)) {

          // Check if the user has entered a valid date and credit card number
          if ((txfCreditCardNo.isEditValid()) && (txfExpiryDate.isEditValid())) {
              String strDate = txfExpiryDate.getText();
              java.sql.Date d = java.sql.Date.valueOf(strDate);
              Calendar enteredDate = Calendar.getInstance();
              enteredDate.setTime(d);

              // Check if the card has not expired already
              Calendar calendar = Calendar.getInstance();
              java.util.Date currentDate = calendar.getTime();
              boolean valid = d.after(currentDate);

              if (valid) {
                  try {
                      rsDetails.moveToInsertRow();
                      rsDetails.updateString(1, txtName.getText());
                      rsDetails.updateLong(2, Long.parseLong(txtContactNo.
                              getText().trim()));
                      rsDetails.updateString(3, txaAddress.getText());
                      rsDetails.updateInt(4, Integer.valueOf(txtNumberOfTickets.
                              getText()));
                      StringTokenizer st = new StringTokenizer(txfCreditCardNo.
                              getText());
                      temp = "";
                      while (st.hasMoreTokens()) {
                          temp = temp + st.nextToken("-");
                      }

                      rsDetails.updateLong(5, Long.parseLong(temp));
                      rsDetails.updateDate(6, d);
                      rsDetails.insertRow();
                      JOptionPane.showMessageDialog(null, "Record Inserted!!");
                      txtName.setText("");
                      txtContactNo.setText("");
                      txaAddress.setText("");
                      txtNumberOfTickets.setText("");
                      txfCreditCardNo.setText("");
                      txfExpiryDate.setText("");
                      txtGoToRecord.setText("");
                  } catch (HeadlessException ex) {
                      ex.printStackTrace();
                  } catch (NumberFormatException ex) {
                      ex.printStackTrace();
                  } catch (SQLException ex) {
                      ex.printStackTrace();
                  }
              } else {
                  JOptionPane.showMessageDialog(null, "Credit card has "
                          + "expired!!");
              }
          }
      }
  }//GEN-LAST:event_btnBookTicketActionPerformed

    /**
     * This is the entry point for the AirlineBooking application.
     *
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TicketBooking().setVisible(true);
            }
        });
    }
    /**
     * Variable to store a reference to a Connection object.
     */
    private Connection cn = null;
    /**
     * Variable to store the URL connection string.
     */
    private final String url = "jdbc:sqlserver://";
    /**
     * Variable to store the IP address of the machine on which SQL Server 2005 database is located.
     */
    private final String serverName = "10.2.1.51";
    /**
     * Variable to store the default port number of SQL Server Database.
     */
    private final String portNumber = "1433";
    /**
     * Variable to store the instance name of the SQL Server.
     */
    private final String instanceName = "martin";
    /**
     * Variable to store the name of the database to connect to DeveloperApps.
     */
    private final String databaseName = "DeveloperApps";
    /**
     * Variable to store the user name to connect to SQL Server.
     */
    private final String userName = "sa";
    /**
     * Variable to store the password to connect to SQL Server.
     */
    private final String password = "playware";
    /**
     * PreparedStatement object to hold a reference to the PreparedStatement object.
     */
    private PreparedStatement pstDetails = null;
    /**
     * Variable to store a reference to a connected ResultSet.
     */
    private ResultSet rsDetails = null;
    /**
     * Variable name to store the number of seconds for calculating the date.
     */
    private long time;
    /**
     * MaskFormatter object to hold a reference to the MaskFormatter object.
     *
     */
    private MaskFormatter cardNumber;
    /**
     * Declare and initailze a String variable.
     *
     */
    private String temp = "";
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBookTicket;
    private javax.swing.JButton btnCancelTicket;
    private javax.swing.JButton btnExit;
    private javax.swing.JButton btnGo;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAddress;
    private javax.swing.JLabel lblContactNumber;
    private javax.swing.JLabel lblCreditCardNo;
    private javax.swing.JLabel lblExpiryDate;
    private javax.swing.JLabel lblGoToRecord;
    private javax.swing.JLabel lblHeading;
    private javax.swing.JLabel lblName;
    private javax.swing.JLabel lblNumberofTickets;
    private javax.swing.JPanel pnlBookingDetails;
    private javax.swing.JPanel pnlGoToRecord;
    private javax.swing.JPanel pnlHeading;
    private javax.swing.JPanel pnlPaymentDetails;
    private javax.swing.JTextArea txaAddress;
    private javax.swing.JFormattedTextField txfCreditCardNo;
    private javax.swing.JFormattedTextField txfExpiryDate;
    private javax.swing.JTextField txtContactNo;
    private javax.swing.JTextField txtGoToRecord;
    private javax.swing.JTextField txtName;
    private javax.swing.JTextField txtNumberOfTickets;
    // End of variables declaration//GEN-END:variables
}
